package utils.query;

import play.db.jpa.Model;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import play.mvc.Scope.Params;

import java.util.List;

/**
 * 查询辅助类
 */
public class QueryHelper {

	/**
	 * 根据页面传递的参数构建JPA查询语句,请优先使用 getPageResults(Class<T> t)
	 * @param t 页面变量前缀
	 * @param <T>
	 * @return ModelQuery
	 */
	public static <T extends Model> ModelQuery<T> getQuery(Class<T> t ){
		List<OrderBy> orderList = OrderBy.BuildFromString(Request.current().querystring);
		ModelQuery<T> query = ModelQuery.query(t,Params.current().all()).orderBy(orderList);
		return query;
	}

	/**
	 *
	 * @param query
	 * @param <T>
	 * @return
	 */
	public static <T extends Model> Page getPageResults(ModelQuery<T> query) {
		Page page = Page.getPageResults(query);
		Response.current().setHeader("content-range", page.toString());
		return page;
	}

	public static <T extends Model> Page getPageResults(Class<T> t) {
		ModelQuery<T> query = QueryHelper.getQuery(t);
		return getPageResults(query);
	}
}
